package com.css.fxfzdzzh.modules.eqLandslide.count.controller;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzdzzh.base.exception.ShpFieldException;
import com.css.fxfzdzzh.base.exception.StrategyFactoryException;
import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.modules.eqLandslide.count.entity.*;
import com.css.fxfzdzzh.modules.eqLandslide.count.param.LargeScreenParam;
import com.css.fxfzdzzh.modules.eqLandslide.count.param.TaskModelParam;
import com.css.fxfzdzzh.modules.eqLandslide.count.service.EqLandslideService;
import com.css.fxfzdzzh.modules.eqLandslide.count.vo.StatisticsAreaVO;
import com.css.fxfzdzzh.modules.eqLandslide.count.vo.SurfaceRuptureZoneVo;
import com.css.fxfzdzzh.modules.hypergraph.service.HypergraphService;
import com.css.fxfzdzzh.util.PlatformObjectUtils;
import com.css.fxfzdzzh.util.PlatformPageUtils;
import com.css.fxfzdzzh.util.ResponseCreator;
import io.swagger.v3.oas.annotations.Operation;
import jdk.nashorn.internal.objects.annotations.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.BufferUnderflowException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: fxfzdzzh
 * @Author: lhl
 * @CreateDate: 2023/2/15 11:21
 */
@RestController
@RequestMapping("/eqLandslide")
@Slf4j
public class EqLandslideController {

    @Resource
    EqLandslideService eqLandslideService;

    @Resource
    HypergraphService hypergraphService;

    @PostMapping("/count1")
    public RestResponse count1(@RequestBody DzzhModelCcfx entity) {
        RestResponse restResponse=null;
        try {
            restResponse=eqLandslideService.count1(entity);
            if (restResponse.getCode() == 200) {
                restResponse.setMessage("层次分析模型计算成功！");
                hypergraphService.getWorkspaceReload("dzzh_result_ccfx");
            }else if (restResponse.getCode() == 401){
                restResponse.setCode(500);
                restResponse.setMessage("您选择的坡度数据版本数据范围不在任务区域内，请重新选择数据版本。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (PlatformObjectUtils.isNotEmpty(e.getLocalizedMessage())){
                restResponse=RestResponse.fail(e.getLocalizedMessage());
            }else {
                restResponse = RestResponse.fail("层次分析模型计算失败！");
            }
        }
        return restResponse;
    }

    @PostMapping("/count2")
    public RestResponse count2(@RequestBody DzzhModelExponential entity) {
        RestResponse restResponse=null;
        try {
            restResponse=eqLandslideService.count2(entity);
            if (restResponse.getCode() == 200) {
                restResponse.setMessage("指数模型计算成功！");
                hypergraphService.getWorkspaceReload("dzzh_result_exponential");
            }else if (restResponse.getCode() == 401){
                restResponse.setCode(500);
                restResponse.setMessage("您选择的坡度数据版本数据范围不在任务区域内，请重新选择数据版本。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("指数模型计算失败！");
        }
        return restResponse;
    }

    @PostMapping("/count3")
    public RestResponse count3(@RequestBody DzzhModelLogisticGrowth entity) {
        RestResponse restResponse=null;
        try {
            restResponse=eqLandslideService.count3(entity);
            if (restResponse.getCode() == 200) {
                restResponse.setMessage("逻辑斯蒂模型计算成功！");
                hypergraphService.getWorkspaceReload("dzzh_result_logistic_growth");
            }else if (restResponse.getCode() == 401){
                restResponse.setCode(500);
                restResponse.setMessage("您选择的坡度数据版本数据范围不在任务区域内，请重新选择数据版本。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("逻辑斯蒂模型计算失败！");
        }
        return restResponse;
    }

    @PostMapping("/count4")
    public RestResponse count4(@RequestBody DzzhModelLoessPlateau entity) {
        RestResponse restResponse=null;
        try {
            restResponse=eqLandslideService.count4(entity);
            if (restResponse.getCode() == 200) {
                restResponse.setMessage("黄土高原模型计算成功！");
                hypergraphService.getWorkspaceReload("dzzh_result_loess_plateau");
            }else if (restResponse.getCode() == 401){
                restResponse.setCode(500);
                restResponse.setMessage("您选择的坡度数据版本数据范围不在任务区域内，请重新选择数据版本。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("黄土高原模型计算失败！");
        }
        return restResponse;
    }

    /**
     * NEWMARK 算法
     */
    @PostMapping("/count5")
    public RestResponse count5(@RequestBody DzzhModelNewmark entity) throws Exception {
        RestResponse restResponse=null;
        try {
            restResponse=eqLandslideService.count5(entity);
            if (restResponse.getCode() == 200) {
                restResponse.setMessage("NEWMARK模型计算成功！");
                hypergraphService.getWorkspaceReload("dzzh_result_newmark");
            }else if (restResponse.getCode() == 401){
                restResponse.setCode(500);
                restResponse.setMessage("您选择的坡度数据版本数据范围不在任务区域内，请重新选择数据版本。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("NEWMARK模型计算失败！");
        }
        return restResponse;
    }

    @GetMapping("/getTaskModelVOPage")
    public RestResponse getTaskModelVOPage(HttpServletRequest request, TaskModelParam param){
        RestResponse restResponse=null;
        try {
            int curPage = Integer.parseInt(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize=Integer.parseInt(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            restResponse=eqLandslideService.getTaskModelVOPage(param,curPage,pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取地震滑坡评估的评估列表失败！");
        }
        return restResponse;
    }

    @GetMapping("/getTaskModelDetail")
    public RestResponse getTaskModelDetail(@RequestParam("taskId") String taskId,@RequestParam("modelType") String modelType){
        RestResponse restResponse=null;
        try {
            restResponse=eqLandslideService.getTaskModelDetail(taskId,modelType);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取地震滑坡评估的结果详情失败！");
        }
        return restResponse;
    }
    @GetMapping("/getTaskModelDetailMil")
    public RestResponse getTaskModelDetailMil(@RequestParam("taskId") String taskId,@RequestParam("dtmId") String dtmId,@RequestParam("modelType") String modelType){
        RestResponse restResponse=null;
        try {
            restResponse=eqLandslideService.getTaskModelDetailMil(taskId,dtmId,modelType);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取地震滑坡评估的结果详情失败！");
        }
        return restResponse;
    }


    @GetMapping("/getDzzhTaskModel")
    public RestResponse getDzzhTaskModel(@RequestParam("taskId") String taskId){
        RestResponse restResponse=null;
        try {
            restResponse=eqLandslideService.getDzzhTaskModel(taskId);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取地震滑坡评估的中间结果失败！");
        }
        return restResponse;
    }

    /**
     * 删除
     */
    @PostMapping("/delDzzhTaskModel")
    public RestResponse delDzzhTaskModel(@RequestBody Map<String,String> map){
        RestResponse restResponse=null;
        try {
            eqLandslideService.delDzzhTaskModel(map.get("dtmId"));
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg","删除成功!");
            restResponse=RestResponse.succeed(jsonObject);
            restResponse.setMessage("删除成功!");
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("删除失败！");
        }
        return restResponse;
    }

    /**
     * 保存为中间结果
     */
    @PostMapping("/updateDzzhTaskModel1")
    public RestResponse updateDzzhTaskModel1(@RequestBody Map<String,String> map){
        RestResponse restResponse=null;
        try {
            eqLandslideService.updateDzzhTaskModel1(map.get("dtmId"),map.get("taskId"),map.get("tab"));
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg","存为地震滑坡评估的中间结果成功!");
            restResponse=RestResponse.succeed(jsonObject);
            restResponse.setMessage("存为地震滑坡评估的中间结果成功!");
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("存为地震滑坡评估的中间结果失败！");
        }
        return restResponse;
    }

    /**
     * 将中间结果替换为最终结果
     */
    @PostMapping("/updateDzzhTaskModel2")
    public RestResponse updateDzzhTaskModel2(@RequestBody Map<String,String> map){
        RestResponse restResponse=null;
        try {
            eqLandslideService.updateDzzhTaskModel2(map.get("dtmId"),map.get("flag"),map.get("taskId"));
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg","替换地震滑坡评估的最终结果成功!");
            restResponse=RestResponse.succeed(jsonObject);
            restResponse.setMessage("替换地震滑坡评估的最终结果成功!");
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("替换地震滑坡评估的最终结果失败！");
        }
        return restResponse;
    }

    @Operation(summary = "归并")
    @GetMapping("/queryDataByVersionCode")
    public RestResponse queryAllLithologyByVersionCode(@RequestParam Map<String,Object> param){
        RestResponse restResponse = eqLandslideService.queryAllLithologyByVersionCode(param);
        if (restResponse.getCode() == 200) {
            //刷新指定超图工作空间数据源数据集
            boolean bool = hypergraphService.getWorkspaceReload("dzzh_lithology_merge_result");
            restResponse.setMessage("黄土高原模型计算成功！");
        }
        return restResponse;
    }

    /**
     * 查询层次分析法结果
     * @param taskId
     * @param proExceed a1:2%、a2:10%、a3:63%
     * @return
     */
    @GetMapping("/getDataByTaskId1")
    public RestResponse getDataByTaskId1(@RequestParam("taskId") String taskId,
                                          @RequestParam("proExceed") String proExceed){
        RestResponse restResponse=null;
        try {
            restResponse=RestResponse.succeed(eqLandslideService.getDataByTaskId1(taskId,proExceed));
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取失败！");
        }
        return restResponse;
    }

    /**
     * 查询黄土高原结果
     * @param taskId
     * @param proExceed a1:2%、a2:10%、a3:63%
     * @return
     */
    @GetMapping("/getDataByTaskId4")
    public RestResponse getDataByTaskId4(@RequestParam("taskId") String taskId,
                                         @RequestParam("proExceed") String proExceed){
        RestResponse restResponse=null;
        try {
            restResponse=RestResponse.succeed(eqLandslideService.getDataByTaskId2(taskId,proExceed));
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取失败！");
        }
        return restResponse;
    }

    /**
     * 查询指数最终结果
     * @param taskId
     * @param dzIntensity
     * @return
     */
    @GetMapping("/getDataByTaskId2")
    public RestResponse getDataByTaskId2(@RequestParam("taskId") String taskId,
                                          @RequestParam("dzIntensity") String dzIntensity){
        RestResponse restResponse=null;
        try {
            restResponse=RestResponse.succeed(eqLandslideService.getDataByTaskId3(taskId,dzIntensity));
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取失败！");
        }
        return restResponse;
    }
    /**
     * 查询逻辑斯蒂最终结果
     * @param taskId
     * @param dzIntensity
     * @return
     */
    @GetMapping("/getDataByTaskId3")
    public RestResponse getDataByTaskId3(@RequestParam("taskId") String taskId,
                                         @RequestParam("dzIntensity") String dzIntensity){
        RestResponse restResponse=null;
        try {
            restResponse=RestResponse.succeed(eqLandslideService.getDataByTaskId4(taskId,dzIntensity));
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取失败！");
        }
        return restResponse;
    }

    /**
     * 查询Newmark结果
     * @param taskId
     * @param proExceed a1:2%、a2:10%、a3:63%
     * @return
     */
    @GetMapping("/getDataByTaskId5")
    public RestResponse getDataByTaskId5(@RequestParam("taskId") String taskId,
                                         @RequestParam("proExceed") String proExceed){
        RestResponse restResponse=null;
        try {
            restResponse=RestResponse.succeed(eqLandslideService.getDataByTaskId5(taskId,proExceed));
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取失败！");
        }
        return restResponse;
    }

    /**
     * 大屏展示-查询逻辑斯蒂结果
     * @param dzIntensity
     * @return
     */
    @GetMapping("/getDataByDzIntensityOfDpzs")
    public JSONObject getDataByDzIntensityOfDpzs(@RequestParam("dzIntensity") String dzIntensity){
        JSONObject jsonObject=new JSONObject();
        try {
            List<String> list = eqLandslideService.getDataByDzIntensityOfDpzs(dzIntensity);
            jsonObject.put("list", list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    //按省统计危险性面积（【地震滑坡-逻辑斯蒂模型】分析评估结果）
    @PostMapping("/countResultAreaByProvince")
    public RestResponse countResultAreaByProvince(@RequestBody Map<String,String> map) {
        RestResponse restResponse=null;
        try {
            restResponse=eqLandslideService.countResultAreaByProvince(map.get("taskId"),map.get("modelType"));
            if (restResponse.getCode() == 200) {
                restResponse.setMessage("按省统计危险性面积成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("按省统计危险性面积失败！");
        }
        return restResponse;
    }
    @PostMapping("/countOtherResultAreaByProvince")
    public RestResponse countOtherResultAreaByProvince(@RequestBody Map<String,String> map) {
        RestResponse restResponse=null;
        try {
            restResponse=eqLandslideService.countOtherResultAreaByProvince(map.get("taskId"),map.get("modelType"));
            if (restResponse.getCode() == 200) {
                restResponse.setMessage("按省统计危险性面积成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("按省统计危险性面积失败！");
        }
        return restResponse;
    }

    @PostMapping("/countOtherResultAreaByCity")
    public RestResponse countOtherResultAreaByCity(@RequestBody Map<String,String> map) {
        RestResponse restResponse=null;
        try {
            restResponse=eqLandslideService.countOtherResultAreaByCity(map.get("taskId"),map.get("modelType"));
            if (restResponse.getCode() == 200) {
                restResponse.setMessage("按市统计危险性面积成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("按市统计危险性面积失败！");
        }
        return restResponse;
    }
    //按市统计危险性面积（【地震滑坡-逻辑斯蒂模型】分析评估结果）
    @PostMapping("/countResultAreaByCity")
    public RestResponse countResultAreaByCity(@RequestBody Map<String,String> map) {
        RestResponse restResponse=null;
        try {
            restResponse=eqLandslideService.countResultAreaByCity(map.get("taskId"),map.get("modelType"));
            if (restResponse.getCode() == 200) {
                restResponse.setMessage("按市统计危险性面积成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("按市统计危险性面积失败！");
        }
        return restResponse;
    }

    //按区县统计危险性面积（【地震滑坡-逻辑斯蒂模型】分析评估结果）
    @PostMapping("/countResultAreaByCounty")
    public RestResponse countResultAreaByCounty(@RequestBody Map<String,String> map) {
        RestResponse restResponse=null;
        try {
            restResponse=eqLandslideService.countResultAreaByCounty(map.get("taskId"),map.get("modelType"));
            if (restResponse.getCode() == 200) {
                restResponse.setMessage("按区县统计危险性面积成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("按区县统计危险性面积失败！");
        }
        return restResponse;
    }

    /**
     * 大屏展示   地震滑坡   砂土液化   软土震陷
     * @return
     */
    @GetMapping("largeScreen")
    public RestResponse largeScreen(LargeScreenParam param){
        try {
            HashMap<String, Object> map = eqLandslideService.largeScreen(param);
            return RestResponse.succeed(map);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return RestResponse.fail("查看失败!");
        }
    }

    /**
     * 大屏展示   地表破裂带
     */
    @GetMapping("getSurfaceRuptureZone")
    public RestResponse getSurfaceRuptureZone(){
        try {
            List<SurfaceRuptureZoneVo> list = eqLandslideService.getSurfaceRuptureZone();
            return RestResponse.succeed(list);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return RestResponse.fail("查看失败!");
        }
    }

    /**
     * 地质灾害   上传历史地表破裂带
     */
    @PostMapping("uploadExcel")
    public RestResponse uploadExcel(@RequestParam MultipartFile file){
        try {
            if (!FileUtil.getSuffix(file.getOriginalFilename()).equals("xls") && !FileUtil.getSuffix(file.getOriginalFilename()).equals("xlsx")) {
                return RestResponse.fail("文件格式不支持!");
            }
            return eqLandslideService.uploadSingleBvInformation(file);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return RestResponse.fail("导入失败!");
        }
    }

    /**
     * 查询危险性面积用于列表展示
     * @param  intensity 6-11
     * @param type 0:按省 1、按市  2、按区县
     */
    @GetMapping("/getStatisticsArea")
    public RestResponse getStatisticsArea(@RequestParam String intensity,@RequestParam String type,
                                          @RequestParam String modelId,@RequestParam String taskId,@RequestParam String modelType) throws Exception{
        List<StatisticsAreaVO> statisticsAreaVOs  = eqLandslideService.getStatisticsArea(intensity, type,modelId,taskId,modelType);
         return ResponseCreator.createSuccessResponse(statisticsAreaVOs);
    }
    @GetMapping("/parseShp")
    public RestResponse parseShp(@RequestParam String fileId,@RequestParam String taskId) {
        if (StringUtils.isBlank(fileId)) {
            return RestResponse.fail("请先上传文件");
        }
        try{
            return eqLandslideService.parseShp(fileId,taskId);
        } catch (BufferUnderflowException | IllegalArgumentException bue) {
            log.error(bue.getMessage(), bue);
            return RestResponse.fail("暂时不支持三维空间数据的导入，请上传二维空间数据，如果您的文件在其他程序打开是平面的展示，请检查是否为三维或者自己强行转为二维后再次尝试");
        } catch (ShpFieldException sfe) {
            log.error(sfe.getMessage(), sfe);
            return RestResponse.fail(sfe.getMessage());
        } catch (IndexOutOfBoundsException ioobe) {
            log.error(ioobe.getMessage(), ioobe);
            return RestResponse.fail("字段数量不符合要求");
        } catch (StrategyFactoryException sfe) {
            log.error(sfe.getMessage(), sfe);
            return RestResponse.fail(sfe.getMessage());
        } catch (DataIntegrityViolationException dive) {
            log.error(dive.getMessage(), dive);
            return RestResponse.fail("数据类型不匹配");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return RestResponse.fail(e.getMessage());
        }

    }
}
